<template>
  <el-dialog v-model="visible" title="📊 查询配置" width="580px">
    <el-form
      ref="formRef"
      :model="formData"
      label-width="100px"
      style="padding: 20px"
    >
      <!-- 是否按销量排序 -->
      <el-form-item label="按销量排序">
        <el-switch
          v-model="formData.sortBySales"
          active-text="是"
          inactive-text="否"
        />
        <div class="form-item-tip">开启后按销量从高到低排序</div>
      </el-form-item>

      <!-- 页码选择 -->
      <el-form-item label="页码">
        <el-select
          v-model="formData.limit"
          placeholder="请选择页码"
          style="width: 100%"
        >
          <el-option
            v-for="item in limitOptions"
            :key="item.value"
            :label="`${item.label} 页`"
            :value="item.value"
          />
        </el-select>
        <div class="form-item-tip">最多可查询 100 页数据</div>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="hide()">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { ref, watch, defineEmits, defineProps, defineExpose } from "vue";
const visible = ref(false);
// ==================== Props ====================
const props = defineProps({
  // 初始表单数据（用于回显）
  initFormData: {
    type: Object,
    default: () => ({}),
  },
  // 可选的页码配置（可自定义）
  limitOptions: {
    type: Array,
    default: () => [
      // 生成1-100
      ...Array.from({ length: 100 }, (_, i) => ({
        label: i + 1,
        value: i + 1,
      })),
    ],
  },
});

const emit = defineEmits(["submit"]);

const formRef = ref(null);
const formData = ref({
  sortBySales: false,
  limit: 1,
});

const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      emit("submit", formData.value);
      visible.value = false;
    } else {
      ElMessage.warning("表单校验失败，请检查输入");
    }
  });
};

const hide = () => {
  console.log("隐藏弹窗");
  visible.value = false;
};

const show = () => {
  const val = props.initFormData;
  formData.value = {
    sortBySales: !!val.sortBySales,
    limit: val.limit || 1,
  };
  visible.value = true;
};

defineExpose({
  show,
  hide,
});
</script>

<style scoped>
.form-item-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}
</style>
